# Copies logs of failed tests.
# Usage: copy_failed_tests.rb directory_with_test_logs out_base_directory.
# out_base_directory should end with path separator.
# Copyright (c) Nikolai Holub.

require 'find'
require 'fileutils'

source_dir = ARGV[0]
out_base_dir = ARGV[1]

failed_test_path_regex = /surefire-reports\/[^\/]+\.txt/
failed_test_content_regex = /FAILURE/

# create output directory
out_dir = out_base_dir + Time.now.strftime("%Y-%m-%d_%H-%M-%S")
FileUtils.mkdir(out_dir)
puts "output directory #{out_dir}"

Find.find(source_dir) do |path|
  Find.prune if File.basename(path) == '.svn' # skip Subversion administrative data

  if path =~ failed_test_path_regex
    content = File.open(path) { |f| f.read };
    if content =~ failed_test_content_regex
      puts "copy #{path}"
      FileUtils.copy(path, out_dir)
    end
  end
end
